3 namespace Wikimedia\Rdbms
;
5 use InvalidArgumentException
;
8 * Helper class used for automatically marking an IDatabase connection as reusable (once it no
9 * longer matters which DB domain is selected) and for deferring the actual network connection
11 * This uses an RAII-style pattern where calling code is expected to keep the returned reference
12 * handle as a function variable that falls out of scope when no longer needed. This avoids the
13 * need for matching reuseConnection() calls for every "return" statement as well as the tedious
18 * function getRowData() {
19 * $conn = $this->lb->getConnectedRef( DB_REPLICA );
20 * $row = $conn->select( ... );
21 * return $row ? (array)$row : false;
22 * // $conn falls out of scope and $this->lb->reuseConnection() gets called
29 class DBConnRef
implements IDatabase
{
30 /** @var ILoadBalancer */
32 /** @var Database|null Live connection handle */
34 /** @var array|null N-tuple of (server index, group, DatabaseDomain|string) */
36 /** @var int One of DB_MASTER/DB_REPLICA */
45 * @param ILoadBalancer $lb Connection manager for $conn
46 * @param IDatabase|array $conn Database or (server index, query groups, domain, flags)
47 * @param int $role The type of connection asked for; one of DB_MASTER/DB_REPLICA
48 * @internal This method should not be called outside of LoadBalancer
50 public function __construct( ILoadBalancer
$lb, $conn, $role ) {
53 if ( $conn instanceof IDatabase
&& !( $conn instanceof DBConnRef
) ) {
54 $this->conn
= $conn; // live handle
55 } elseif ( is_array( $conn ) && count( $conn ) >= 4 && $conn[self
::FLD_DOMAIN
] !== false ) {
56 $this->params
= $conn;
58 throw new InvalidArgumentException( "Missing lazy connection arguments." );
62 function __call( $name, array $arguments ) {
63 if ( $this->conn
=== null ) {
64 list( $index, $groups, $wiki, $flags ) = $this->params
;
65 $this->conn
= $this->lb
->getConnection( $index, $groups, $wiki, $flags );
68 return $this->conn
->$name( ...$arguments );
72 * @return int DB_MASTER when this *requires* the master DB, otherwise DB_REPLICA
75 public function getReferenceRole() {
79 public function getServerInfo() {
80 return $this->__call( __FUNCTION__
, func_get_args() );
83 public function bufferResults( $buffer = null ) {
84 return $this->__call( __FUNCTION__
, func_get_args() );
87 public function trxLevel() {
88 return $this->__call( __FUNCTION__
, func_get_args() );
91 public function trxTimestamp() {
92 return $this->__call( __FUNCTION__
, func_get_args() );
95 public function explicitTrxActive() {
96 return $this->__call( __FUNCTION__
, func_get_args() );
99 public function assertNoOpenTransactions() {
100 return $this->__call( __FUNCTION__
, func_get_args() );
103 public function tablePrefix( $prefix = null ) {
104 if ( $this->conn
=== null && $prefix === null ) {
105 $domain = DatabaseDomain
::newFromId( $this->params
[self
::FLD_DOMAIN
] );
106 // Avoid triggering a database connection
107 return $domain->getTablePrefix();
108 } elseif ( $this->conn
!== null && $prefix === null ) {
109 // This will just return the prefix
110 return $this->__call( __FUNCTION__
, func_get_args() );
112 // Disallow things that might confuse the LoadBalancer tracking
113 throw new DBUnexpectedError( $this, "Database selection is disallowed to enable reuse." );
116 public function dbSchema( $schema = null ) {
117 if ( $this->conn
=== null && $schema === null ) {
118 $domain = DatabaseDomain
::newFromId( $this->params
[self
::FLD_DOMAIN
] );
119 // Avoid triggering a database connection
120 return $domain->getSchema();
121 } elseif ( $this->conn
!== null && $schema === null ) {
122 // This will just return the schema
123 return $this->__call( __FUNCTION__
, func_get_args() );
125 // Disallow things that might confuse the LoadBalancer tracking
126 throw new DBUnexpectedError( $this, "Database selection is disallowed to enable reuse." );
129 public function getLBInfo( $name = null ) {
130 return $this->__call( __FUNCTION__
, func_get_args() );
133 public function setLBInfo( $nameOrArray, $value = null ) {
134 // Disallow things that might confuse the LoadBalancer tracking
135 throw new DBUnexpectedError( $this, "Changing LB info is disallowed to enable reuse." );
138 public function setLazyMasterHandle( IDatabase
$conn ) {
139 // Disallow things that might confuse the LoadBalancer tracking
140 throw new DBUnexpectedError( $this, "Database injection is disallowed to enable reuse." );
143 public function implicitOrderby() {
144 return $this->__call( __FUNCTION__
, func_get_args() );
147 public function lastQuery() {
148 return $this->__call( __FUNCTION__
, func_get_args() );
151 public function lastDoneWrites() {
152 return $this->__call( __FUNCTION__
, func_get_args() );
155 public function writesPending() {
156 return $this->__call( __FUNCTION__
, func_get_args() );
159 public function preCommitCallbacksPending() {
160 return $this->__call( __FUNCTION__
, func_get_args() );
163 public function writesOrCallbacksPending() {
164 return $this->__call( __FUNCTION__
, func_get_args() );
167 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
168 return $this->__call( __FUNCTION__
, func_get_args() );
171 public function pendingWriteCallers() {
172 return $this->__call( __FUNCTION__
, func_get_args() );
175 public function pendingWriteRowsAffected() {
176 return $this->__call( __FUNCTION__
, func_get_args() );
179 public function isOpen() {
180 return $this->__call( __FUNCTION__
, func_get_args() );
183 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
184 return $this->__call( __FUNCTION__
, func_get_args() );
187 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
188 return $this->__call( __FUNCTION__
, func_get_args() );
191 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
192 return $this->__call( __FUNCTION__
, func_get_args() );
195 public function getFlag( $flag ) {
196 return $this->__call( __FUNCTION__
, func_get_args() );
199 public function getProperty( $name ) {
200 return $this->__call( __FUNCTION__
, func_get_args() );
203 public function getDomainID() {
204 if ( $this->conn
=== null ) {
205 $domain = $this->params
[self
::FLD_DOMAIN
];
206 // Avoid triggering a database connection
207 return $domain instanceof DatabaseDomain ?
$domain->getId() : $domain;
210 return $this->__call( __FUNCTION__
, func_get_args() );
213 public function getType() {
214 if ( $this->conn
=== null ) {
215 // Avoid triggering a database connection
216 if ( $this->params
[self
::FLD_INDEX
] === ILoadBalancer
::DB_MASTER
) {
217 $index = $this->lb
->getWriterIndex();
219 $index = $this->params
[self
::FLD_INDEX
];
222 // In theory, if $index is DB_REPLICA, the type could vary
223 return $this->lb
->getServerType( $index );
227 return $this->__call( __FUNCTION__
, func_get_args() );
230 public function fetchObject( $res ) {
231 return $this->__call( __FUNCTION__
, func_get_args() );
234 public function fetchRow( $res ) {
235 return $this->__call( __FUNCTION__
, func_get_args() );
238 public function numRows( $res ) {
239 return $this->__call( __FUNCTION__
, func_get_args() );
242 public function numFields( $res ) {
243 return $this->__call( __FUNCTION__
, func_get_args() );
246 public function fieldName( $res, $n ) {
247 return $this->__call( __FUNCTION__
, func_get_args() );
250 public function insertId() {
251 return $this->__call( __FUNCTION__
, func_get_args() );
254 public function dataSeek( $res, $row ) {
255 return $this->__call( __FUNCTION__
, func_get_args() );
258 public function lastErrno() {
259 return $this->__call( __FUNCTION__
, func_get_args() );
262 public function lastError() {
263 return $this->__call( __FUNCTION__
, func_get_args() );
266 public function affectedRows() {
267 return $this->__call( __FUNCTION__
, func_get_args() );
270 public function getSoftwareLink() {
271 return $this->__call( __FUNCTION__
, func_get_args() );
274 public function getServerVersion() {
275 return $this->__call( __FUNCTION__
, func_get_args() );
278 public function close() {
279 throw new DBUnexpectedError( $this->conn
, 'Cannot close shared connection.' );
282 public function query( $sql, $fname = __METHOD__
, $flags = 0 ) {
283 if ( $this->role
!== ILoadBalancer
::DB_MASTER
) {
284 $flags |
= IDatabase
::QUERY_REPLICA_ROLE
;
287 return $this->__call( __FUNCTION__
, [ $sql, $fname, $flags ] );
290 public function freeResult( $res ) {
291 return $this->__call( __FUNCTION__
, func_get_args() );
294 public function selectField(
295 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
297 return $this->__call( __FUNCTION__
, func_get_args() );
300 public function selectFieldValues(
301 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
303 return $this->__call( __FUNCTION__
, func_get_args() );
306 public function select(
307 $table, $vars, $conds = '', $fname = __METHOD__
,
308 $options = [], $join_conds = []
310 return $this->__call( __FUNCTION__
, func_get_args() );
313 public function selectSQLText(
314 $table, $vars, $conds = '', $fname = __METHOD__
,
315 $options = [], $join_conds = []
317 return $this->__call( __FUNCTION__
, func_get_args() );
320 public function limitResult( $sql, $limit, $offset = false ) {
321 return $this->__call( __FUNCTION__
, func_get_args() );
324 public function selectRow(
325 $table, $vars, $conds, $fname = __METHOD__
,
326 $options = [], $join_conds = []
328 return $this->__call( __FUNCTION__
, func_get_args() );
331 public function estimateRowCount(
332 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
334 return $this->__call( __FUNCTION__
, func_get_args() );
337 public function selectRowCount(
338 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
340 return $this->__call( __FUNCTION__
, func_get_args() );
343 public function lockForUpdate(
344 $table, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
346 $this->assertRoleAllowsWrites();
348 return $this->__call( __FUNCTION__
, func_get_args() );
351 public function fieldExists( $table, $field, $fname = __METHOD__
) {
352 return $this->__call( __FUNCTION__
, func_get_args() );
355 public function indexExists( $table, $index, $fname = __METHOD__
) {
356 return $this->__call( __FUNCTION__
, func_get_args() );
359 public function tableExists( $table, $fname = __METHOD__
) {
360 return $this->__call( __FUNCTION__
, func_get_args() );
363 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
364 $this->assertRoleAllowsWrites();
366 return $this->__call( __FUNCTION__
, func_get_args() );
369 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
370 $this->assertRoleAllowsWrites();
372 return $this->__call( __FUNCTION__
, func_get_args() );
375 public function makeList( $a, $mode = self
::LIST_COMMA
) {
376 return $this->__call( __FUNCTION__
, func_get_args() );
379 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
380 return $this->__call( __FUNCTION__
, func_get_args() );
383 public function aggregateValue( $valuedata, $valuename = 'value' ) {
384 return $this->__call( __FUNCTION__
, func_get_args() );
387 public function bitNot( $field ) {
388 return $this->__call( __FUNCTION__
, func_get_args() );
391 public function bitAnd( $fieldLeft, $fieldRight ) {
392 return $this->__call( __FUNCTION__
, func_get_args() );
395 public function bitOr( $fieldLeft, $fieldRight ) {
396 return $this->__call( __FUNCTION__
, func_get_args() );
399 public function buildConcat( $stringList ) {
400 return $this->__call( __FUNCTION__
, func_get_args() );
403 public function buildGroupConcatField(
404 $delim, $table, $field, $conds = '', $join_conds = []
406 return $this->__call( __FUNCTION__
, func_get_args() );
409 public function buildSubstring( $input, $startPosition, $length = null ) {
410 return $this->__call( __FUNCTION__
, func_get_args() );
413 public function buildStringCast( $field ) {
414 return $this->__call( __FUNCTION__
, func_get_args() );
417 public function buildIntegerCast( $field ) {
418 return $this->__call( __FUNCTION__
, func_get_args() );
421 public function buildSelectSubquery(
422 $table, $vars, $conds = '', $fname = __METHOD__
,
423 $options = [], $join_conds = []
425 return $this->__call( __FUNCTION__
, func_get_args() );
428 public function databasesAreIndependent() {
429 return $this->__call( __FUNCTION__
, func_get_args() );
432 public function selectDB( $db ) {
433 // Disallow things that might confuse the LoadBalancer tracking
434 throw new DBUnexpectedError( $this, "Database selection is disallowed to enable reuse." );
437 public function selectDomain( $domain ) {
438 // Disallow things that might confuse the LoadBalancer tracking
439 throw new DBUnexpectedError( $this, "Database selection is disallowed to enable reuse." );
442 public function getDBname() {
443 if ( $this->conn
=== null ) {
444 $domain = DatabaseDomain
::newFromId( $this->params
[self
::FLD_DOMAIN
] );
445 // Avoid triggering a database connection
446 return $domain->getDatabase();
449 return $this->__call( __FUNCTION__
, func_get_args() );
452 public function getServer() {
453 return $this->__call( __FUNCTION__
, func_get_args() );
456 public function addQuotes( $s ) {
457 return $this->__call( __FUNCTION__
, func_get_args() );
460 public function addIdentifierQuotes( $s ) {
461 return $this->__call( __FUNCTION__
, func_get_args() );
464 public function buildLike( $param ) {
465 return $this->__call( __FUNCTION__
, func_get_args() );
468 public function anyChar() {
469 return $this->__call( __FUNCTION__
, func_get_args() );
472 public function anyString() {
473 return $this->__call( __FUNCTION__
, func_get_args() );
476 public function nextSequenceValue( $seqName ) {
477 $this->assertRoleAllowsWrites();
479 return $this->__call( __FUNCTION__
, func_get_args() );
482 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
483 $this->assertRoleAllowsWrites();
485 return $this->__call( __FUNCTION__
, func_get_args() );
488 public function upsert(
489 $table, array $rows, $uniqueIndexes, array $set, $fname = __METHOD__
491 $this->assertRoleAllowsWrites();
493 return $this->__call( __FUNCTION__
, func_get_args() );
496 public function deleteJoin(
497 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
499 $this->assertRoleAllowsWrites();
501 return $this->__call( __FUNCTION__
, func_get_args() );
504 public function delete( $table, $conds, $fname = __METHOD__
) {
505 $this->assertRoleAllowsWrites();
507 return $this->__call( __FUNCTION__
, func_get_args() );
510 public function insertSelect(
511 $destTable, $srcTable, $varMap, $conds,
512 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
514 $this->assertRoleAllowsWrites();
516 return $this->__call( __FUNCTION__
, func_get_args() );
519 public function unionSupportsOrderAndLimit() {
520 return $this->__call( __FUNCTION__
, func_get_args() );
523 public function unionQueries( $sqls, $all ) {
524 return $this->__call( __FUNCTION__
, func_get_args() );
527 public function unionConditionPermutations(
528 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
529 $options = [], $join_conds = []
531 return $this->__call( __FUNCTION__
, func_get_args() );
534 public function conditional( $cond, $trueVal, $falseVal ) {
535 return $this->__call( __FUNCTION__
, func_get_args() );
538 public function strreplace( $orig, $old, $new ) {
539 return $this->__call( __FUNCTION__
, func_get_args() );
542 public function getServerUptime() {
543 return $this->__call( __FUNCTION__
, func_get_args() );
546 public function wasDeadlock() {
547 return $this->__call( __FUNCTION__
, func_get_args() );
550 public function wasLockTimeout() {
551 return $this->__call( __FUNCTION__
, func_get_args() );
554 public function wasConnectionLoss() {
555 return $this->__call( __FUNCTION__
, func_get_args() );
558 public function wasReadOnlyError() {
559 return $this->__call( __FUNCTION__
, func_get_args() );
562 public function wasErrorReissuable() {
563 return $this->__call( __FUNCTION__
, func_get_args() );
566 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
567 return $this->__call( __FUNCTION__
, func_get_args() );
570 public function getReplicaPos() {
571 return $this->__call( __FUNCTION__
, func_get_args() );
574 public function getMasterPos() {
575 return $this->__call( __FUNCTION__
, func_get_args() );
578 public function serverIsReadOnly() {
579 return $this->__call( __FUNCTION__
, func_get_args() );
582 public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
583 // DB_REPLICA role: caller might want to refresh cache after a REPEATABLE-READ snapshot
584 return $this->__call( __FUNCTION__
, func_get_args() );
587 public function onTransactionCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
588 // DB_REPLICA role: caller might want to refresh cache after a REPEATABLE-READ snapshot
589 return $this->__call( __FUNCTION__
, func_get_args() );
592 public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
593 return $this->onTransactionCommitOrIdle( $callback, $fname );
596 public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
597 // DB_REPLICA role: caller might want to refresh cache after a cache mutex is released
598 return $this->__call( __FUNCTION__
, func_get_args() );
601 public function onAtomicSectionCancel( callable
$callback, $fname = __METHOD__
) {
602 return $this->__call( __FUNCTION__
, func_get_args() );
605 public function setTransactionListener( $name, callable
$callback = null ) {
606 return $this->__call( __FUNCTION__
, func_get_args() );
609 public function startAtomic(
610 $fname = __METHOD__
, $cancelable = IDatabase
::ATOMIC_NOT_CANCELABLE
612 // Don't call assertRoleAllowsWrites(); caller might want a REPEATABLE-READ snapshot
613 return $this->__call( __FUNCTION__
, func_get_args() );
616 public function endAtomic( $fname = __METHOD__
) {
617 // Don't call assertRoleAllowsWrites(); caller might want a REPEATABLE-READ snapshot
618 return $this->__call( __FUNCTION__
, func_get_args() );
621 public function cancelAtomic( $fname = __METHOD__
, AtomicSectionIdentifier
$sectionId = null ) {
622 // Don't call assertRoleAllowsWrites(); caller might want a REPEATABLE-READ snapshot
623 return $this->__call( __FUNCTION__
, func_get_args() );
626 public function doAtomicSection(
627 $fname, callable
$callback, $cancelable = self
::ATOMIC_NOT_CANCELABLE
629 // Don't call assertRoleAllowsWrites(); caller might want a REPEATABLE-READ snapshot
630 return $this->__call( __FUNCTION__
, func_get_args() );
633 public function begin( $fname = __METHOD__
, $mode = IDatabase
::TRANSACTION_EXPLICIT
) {
634 return $this->__call( __FUNCTION__
, func_get_args() );
637 public function commit( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
638 return $this->__call( __FUNCTION__
, func_get_args() );
641 public function rollback( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
642 return $this->__call( __FUNCTION__
, func_get_args() );
645 public function flushSnapshot( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
646 return $this->__call( __FUNCTION__
, func_get_args() );
649 public function timestamp( $ts = 0 ) {
650 return $this->__call( __FUNCTION__
, func_get_args() );
653 public function timestampOrNull( $ts = null ) {
654 return $this->__call( __FUNCTION__
, func_get_args() );
657 public function ping( &$rtt = null ) {
658 return func_num_args()
659 ?
$this->__call( __FUNCTION__
, [ &$rtt ] )
660 : $this->__call( __FUNCTION__
, [] ); // method cares about null vs missing
663 public function getLag() {
664 return $this->__call( __FUNCTION__
, func_get_args() );
667 public function getSessionLagStatus() {
668 return $this->__call( __FUNCTION__
, func_get_args() );
671 public function maxListLen() {
672 return $this->__call( __FUNCTION__
, func_get_args() );
675 public function encodeBlob( $b ) {
676 return $this->__call( __FUNCTION__
, func_get_args() );
679 public function decodeBlob( $b ) {
680 return $this->__call( __FUNCTION__
, func_get_args() );
683 public function setSessionOptions( array $options ) {
684 return $this->__call( __FUNCTION__
, func_get_args() );
687 public function setSchemaVars( $vars ) {
688 return $this->__call( __FUNCTION__
, func_get_args() );
691 public function lockIsFree( $lockName, $method ) {
692 $this->assertRoleAllowsWrites();
694 return $this->__call( __FUNCTION__
, func_get_args() );
697 public function lock( $lockName, $method, $timeout = 5 ) {
698 $this->assertRoleAllowsWrites();
700 return $this->__call( __FUNCTION__
, func_get_args() );
703 public function unlock( $lockName, $method ) {
704 $this->assertRoleAllowsWrites();
706 return $this->__call( __FUNCTION__
, func_get_args() );
709 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
710 $this->assertRoleAllowsWrites();
712 return $this->__call( __FUNCTION__
, func_get_args() );
715 public function namedLocksEnqueue() {
716 return $this->__call( __FUNCTION__
, func_get_args() );
719 public function getInfinity() {
720 return $this->__call( __FUNCTION__
, func_get_args() );
723 public function encodeExpiry( $expiry ) {
724 return $this->__call( __FUNCTION__
, func_get_args() );
727 public function decodeExpiry( $expiry, $format = TS_MW
) {
728 return $this->__call( __FUNCTION__
, func_get_args() );
731 public function setBigSelects( $value = true ) {
732 return $this->__call( __FUNCTION__
, func_get_args() );
735 public function isReadOnly() {
736 return $this->__call( __FUNCTION__
, func_get_args() );
739 public function setTableAliases( array $aliases ) {
740 return $this->__call( __FUNCTION__
, func_get_args() );
743 public function setIndexAliases( array $aliases ) {
744 return $this->__call( __FUNCTION__
, func_get_args() );
747 public function __toString() {
748 if ( $this->conn
=== null ) {
749 // spl_object_id is PHP >= 7.2
750 $id = function_exists( 'spl_object_id' )
751 ?
spl_object_id( $this )
752 : spl_object_hash( $this );
754 return $this->getType() . ' object #' . $id;
757 return $this->__call( __FUNCTION__
, func_get_args() );
761 * Error out if the role is not DB_MASTER
763 * Note that the underlying connection may or may not itself be read-only.
764 * It could even be to a writable master (both server-side and to the application).
765 * This error is meant for the case when a DB_REPLICA handle was requested but a
766 * a write was attempted on that handle regardless.
768 * In configurations where the master DB has some generic read load or is the only server,
769 * DB_MASTER/DB_REPLICA will sometimes (or always) use the same connection to the master DB.
770 * This does not effect the role of DBConnRef instances.
771 * @throws DBReadOnlyRoleError
773 protected function assertRoleAllowsWrites() {
774 // DB_MASTER is "prima facie" writable
775 if ( $this->role
!== ILoadBalancer
::DB_MASTER
) {
776 throw new DBReadOnlyRoleError( $this->conn
, "Cannot write with role DB_REPLICA" );
781 * Clean up the connection when out of scope
783 function __destruct() {
785 $this->lb
->reuseConnection( $this->conn
);
792 * @deprecated since 1.29
794 class_alias( DBConnRef
::class, 'DBConnRef' );